<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
<head>
  <link href="//gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="generator" content="Hugo 0.69.0" />

  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>本地文件上传 &middot; 我的博客</title>

  
  <link type="text/css" rel="stylesheet" href="/myhugo/css/print.css" media="print">
  <link type="text/css" rel="stylesheet" href="/myhugo/css/poole.css">
  <link type="text/css" rel="stylesheet" href="/myhugo/css/syntax.css">
  <link type="text/css" rel="stylesheet" href="/myhugo/css/hyde.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abril+Fatface|PT+Sans:400,400i,700">


  
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/apple-touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="/favicon.png">

  
  
</head>

  <body class="theme-base-0d ">
  <aside class="sidebar">
  <div class="container sidebar-sticky">
    <div class="sidebar-about">
      <a href="/myhugo/"><h1>我的博客</h1></a>
      <p class="lead">
       小白的逆袭之旅 
      </p>
    </div>

    <nav>
      <ul class="sidebar-nav">
        <li><a href="/myhugo/">Home</a> </li>
        
      </ul>
    </nav>

    <p>&copy; 2020. All rights reserved. </p>
  </div>
</aside>

    <main class="content container">
    <div class="post">
  <h1>本地文件上传</h1>
  <time datetime=2020-04-29T17:03:36&#43;0800 class="post-date">Wed, Apr 29, 2020</time>
  <h3 id="1准备工作">1.准备工作</h3>
<pre><code>STATIC_URL = '/static/'

STATICFILES_DIRS=[
     os.path.join(BASE_DIR,'static')
]

#定义上传文件夹的路径
UPLOAD_ROOT = os.path.join(BASE_DIR,'static/upload')
</code></pre><h3 id="12view视图">1.2view视图</h3>
<pre><code>#导包
import uuid
# 导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os
# 导入类视图
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView

(一)
class UploadFile(APIView):

    def post(self,request):
        #接受参数
        myfile = request.FILES.get('file')
        print(myfile)                         ps:如果上传的图片是中文名称， QQ图片20200210134035.jpg&quot;，需要将 &quot; 替换掉
        # 上传的文件是一个对象
        myfilename=myfile.name.replace('&quot;','')

        #建立文件流对象   使用相对路径引入       二进制流写入
        f = open(os.path.join(UPLOAD_ROOT,myfilename),'wb')
        #写入
        for chunk in myfile.chunks():
            f.write(chunk)
        f.close()
        return Response({'filename':myfilename})


(二)
class UploadFile(APIView):

    def post(self,request):
        #接受参数
        myfile = request.FILES.get('file')
        myfile.name=str(uuid.uuid4())+'.png'

        #建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT,'',myfile.name),'wb')
        #写入
        for chunk in myfile.chunks():
            f.write(chunk)
        f.close()
        return Response({'filename':myfile.name})
</code></pre><h3 id="13vue">1.3vue</h3>
<pre><code>&lt;template&gt;
  &lt;div&gt;
	  &lt;myheader&gt;&lt;/myheader&gt;

	&lt;section class=&quot;featured-block text-center&quot;&gt;
		&lt;div class=&quot;container&quot;&gt;

      &lt;div&gt;
        &lt;img :src=&quot;src&quot;&gt;                //自适应
        &lt;Avatar :src='src' :width='150' fit='fill'&gt;&lt;/Avatar&gt;
      &lt;/div&gt;

      &lt;table&gt;
        &lt;tr&gt;
          &lt;td&gt;用户头像&lt;/td&gt;
          &lt;input type=&quot;file&quot; @change=&quot;upload&quot;&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
			

		&lt;/div&gt;
	&lt;/section&gt;
    
&lt;/div&gt;
  
&lt;/template&gt;


 
&lt;script&gt;
//导入组件
import myheader from './myheader.vue'
export default {
  data () {
    return {
      src:''

    }
  },
  components: {
    'myheader':myheader,
  },
  methods: {
    //定义提交事件
    upload(e){
      //获取文件
      let file = e.target.files[0]
      //声明表单参数
      let data = new FormData()
                //文件key(要和后端接受文件参数名一致) 文件实体，文件名称
      data.append('file',file,file.name)
      //声明请求头
      let config = {headers:{'Content-Type':'multipart/form-data'}}   
      this.axios.post('http://127.0.0.1:8000/upload/',data,config)
      .then(res=&gt;{
        console.log(res)
        this.src = 'http://127.0.0.1:8000/static/upload/'+res.data.filename
      })
    }


  },
 
}


&lt;/script&gt;
 
&lt;style&gt;
/* //标签选择器 */
td{
  padding: 10px
}
.imgcode{
  cursor: pointer;
}


&lt;/style&gt;
</code></pre><pre><code>from PIL import Image,ImageDraw
# 读图 添加水印
im = Image.open('./static/upload/2020-01-25-15-45-24_0.png')
print(im.format,im.size,im.mode)
#生成画笔
draw = ImageDraw.Draw(im)
#绘制
draw.text((1330,740),'1907',fill=(76,234,124,180))
im.show()
</code></pre><pre><code>import cv2
#图像压缩
#读图
img = cv2.imread('./static/upload/2020-01-25-15-45-24_0.png')
#压缩 0-9 等级越高越次
cv2.imwrite('./static/upload/2020-01-25-15-45-24_01.png',img,[cv2.IMWRITE_PNG_COMPRESSION,5])
#jpg  0-100
cv2.imwrite('./static/upload/2020-01-25-15-45-24_03.jpg',img,[cv2.IMWRITE_JPEG_CHROMA_QUALITY,50])
</code></pre>
</div>


    </main>

    
  </body>
</html>
